package com.gage.controller.admin;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import net.sf.json.JSONArray;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gage.controller.base.BaseController;
import com.gage.commons.result.PageInfo;
import com.gage.commons.result.Tree;
import com.gage.commons.utils.StringUtils;
import com.gage.model.BsDepartment;
import com.gage.model.BsDepartmentUser;
import com.gage.model.vo.UserVo;
import com.gage.service.IBsDepartmentService;
import com.gage.service.IUserService;
/**
 * <p>
 * 院系管理控制器
 * </p>
 * @author kairu.lu
 * @since 2017-04-26
 */
@Controller
@RequestMapping("/admin/department")
public class BsDepartmentController extends BaseController{
	@Autowired
	private IBsDepartmentService departmentService;
    @Autowired
    private IUserService userService;
	@GetMapping("/index")
    public String create(Model model) {
		if (this.getUserType()==1) {
			model.addAttribute("hidden", true);
		}
		
        return "admin/department/index";
    }
	 /**
		 * 加载树
		 * @author lkr
		 * @date:20170512
		 * @param request
		 * @param id
		 * @return
		 */
		@PostMapping("/tree")
	    @ResponseBody
		public Object getDepartmentTree(HttpServletRequest request)
		{
			int departmentId=0;
			int grade=0;
			if (this.getUserType()==1) {
				departmentId=this.getDepartmentId();
				grade=1;
			}
			return departmentService.selectDepartmentTree(grade,departmentId);
		}
		/**
		 * 院系列表
	     * @author lkr
	     * @date:20170512
		 * @param department
		 * @param page
		 * @param rows
		 * @param sort
		 * @param order
		 * @return
		 */
	    @PostMapping("/dataGrid")
	    @ResponseBody
	    public Object dataGrid(BsDepartment department, Integer page, Integer rows, String sort, String order) {
	        PageInfo pageInfo = new PageInfo(page, rows, sort, order);
	        Map<String, Object> condition = new HashMap<String, Object>();
	        int departmentId=0;
			if (this.getUserType()==1) {
				departmentId=this.getDepartmentId();
				condition.put("parentid",departmentId);
			}else if (StringUtils.isNotEmpty(department.getParentid())) {
					condition.put("parentid", department.getParentid());
	        }
	        if (StringUtils.isNotEmpty(department.getDepartmentName())) {
	            condition.put("departmentName", department.getDepartmentName());
	        }
	        pageInfo.setCondition(condition);
	        return  departmentService.selectDataGrid(pageInfo);
	    }
	 /**
     * 添加院系信息页
      * @author lkr
      * @date:20170512
     * @return
     */
    @GetMapping("/add")
    public String addPage(String departmentId,Model model) {
    	int userId=0;
		if (this.getUserType()==1) {
			userId=this.getDepartmentId();
		}
    	List<BsDepartment> departmentList=departmentService.selectDepartmentList(0,userId);
    	model.addAttribute("departmentList",departmentList);
        return "admin/department/edit";
    }
    /**
     * 编辑院系页
     *
     * @return
     */
    @GetMapping("/edit")
    public String editPage(String id,Model model) {
    	if (StringUtils.isNotBlank(id)) {
    		int cuurid=Integer.parseInt(id);
    		int departmentId=0;
			if (this.getUserType()==1) {
				departmentId=this.getDepartmentId();
			}
    		List<BsDepartment> departmentList=departmentService.selectDepartmentList(0,departmentId);
    		model.addAttribute("departmentList",departmentList);
			BsDepartment department=departmentService.selectDepartmentById(cuurid);
			model.addAttribute("department",department);
			model.addAttribute("logo",department.getLogopath()+"/"+department.getLogoname());
		}
        return "admin/department/edit";
    }
    /**
     * @author lkr
     * @date:20170512
     * @param article
     * @param result
     * @return
     */
    @PostMapping("/save")
    @ResponseBody
	public Object save(@Valid BsDepartment department, BindingResult result){
    	if (result.hasErrors()) {
            return renderError(result);
        }
    	if (StringUtils.isEmpty(department.getIcon())) {
    		department.setIcon("fi-results-demographics");
        }
    	if (StringUtils.isEmpty(department.getParentid())) {
    		int departmentId=0;
			if (this.getUserType()==1) {//判断用户属于院系管理用户
				departmentId=this.getDepartmentId();
				department.setParentid(departmentId);
			}else {
				department.setParentid(department.getParentid());
			}
    		department.setGrade(0);
        }else {
        	department.setGrade(1);
		}
    	if (StringUtils.isNotEmpty(department.getId())) {
    		departmentService.updateById(department);
		}else {
			department.setCreatedate(new Date());
			departmentService.insert(department);
		}
    	return resultJson("1","信息保存成功","");
    }
    /**
     * 删除
     * @author lkr
 	 * @date:20170512
     * @param id
     * @return
     */
    @PostMapping("/delete")
    @ResponseBody
    public Object delete(String id) {
    	if (StringUtils.isNotEmpty(id)) {
	    	String[] ids = id.split(",");
	    	List<String> list = new ArrayList<String>();
			for (int i = 0; i < ids.length; i++){
				list.add(ids[i].trim());
				List<BsDepartment> o=departmentService.selectDepartmentList(0,Integer.parseInt(ids[i].toString()));
				if (o.size()>0) {
					return renderError("该记录存在子记录，不能删除！");
				}else {
					BsDepartment de=departmentService.selectDepartmentById(Integer.parseInt(ids[i].toString()));
					de.setStatus(0);
					//departmentService.deleteById(Integer.parseInt(ids[i].toString()));
					departmentService.updateById(de);
				}
			}
			return renderSuccess("成功删除"+ids.length+"条信息！");
    	}
    	return renderError("删除失败，删除操作出错！");
	}
    
    /**
     * 分配用户页
     *
     * @return
     */
    @GetMapping("/assignuser")
    public String assignUser(Long id,Model model) {
        return "admin/department/assignuser";
    }
    /**
     * 分配用户页
     *
     * @return
     */
    @GetMapping("/userList")
    public String userList(String id,Model model) {
    	model.addAttribute("departmentId", id);
        return "admin/department/userlist";
    }
    /**
     * 用户列表
     *
     * @param userVo
     * @param page
     * @param rows
     * @param sort
     * @param order
     * @return
     */
    @PostMapping("/assignUserList")
    @ResponseBody
    public Object assignUserList(UserVo userVo, Integer page, Integer rows, String sort, String order) {
        PageInfo pageInfo = new PageInfo(page, rows, sort, order);
        Map<String, Object> condition = new HashMap<String, Object>();

        if (StringUtils.isNotBlank(userVo.getName())) {
            condition.put("name", userVo.getName());
        }
        condition.put("organizationId",7);//默认获取大学部的用户
        condition.put("roleId",9);//默认获取大学部管理员的用户
        if (userVo.getCreatedateStart() != null) {
            condition.put("startTime", userVo.getCreatedateStart());
        }
        if (userVo.getCreatedateEnd() != null) {
            condition.put("endTime", userVo.getCreatedateEnd());
        }
        pageInfo.setCondition(condition);
        return departmentService.selectAssignUserPage(pageInfo);
    }
    /**
     * @author lkr
     * @date:20170512
     * @param article
     * @param result
     * @return
     */
    @PostMapping("/saveAssignUser")
    @ResponseBody
	public Object saveAssignUser(@Valid BsDepartmentUser departmentUser,Long departmentIds, BindingResult result){
    	if (result.hasErrors()) {
            return renderError(result);
        }
    	int count=departmentService.getAssignUserCount(departmentIds);
    	if (count>5) {
    		return resultJson("1","系统最多只能分配5个管理账户！","");
		}
    	departmentUser.setDepartmentId(departmentIds);
    	departmentService.insertDepartmentUser(departmentUser);
    	return resultJson("1","信息保存成功","");
    }
    /**
     * 用户列表
     *
     * @param userVo
     * @param page
     * @param rows
     * @param sort
     * @param order
     * @return
     */
    @PostMapping("/getDepartmentUserList")
    @ResponseBody
    public Object getDepartmentUserByDepartmentId(@Valid String departmentId, Integer page, Integer rows, String sort, String order) {
        PageInfo pageInfo = new PageInfo(page, rows, sort, order);
        Map<String, Object> condition = new HashMap<String, Object>();

        if (StringUtils.isNotEmpty(departmentId)) {
            condition.put("departmentId", departmentId);
        }
       // condition.put("organizationId",7);//默认获取大学部的用户
        pageInfo.setCondition(condition);
        return  departmentService.getDepartmentUserByDepartmentId(pageInfo);
    }
    /**
     * 删除
     * @author lkr
 	 * @date:20170512
     * @param id
     * @return
     */
    @PostMapping("/removeAssignUser")
    @ResponseBody
    public Object removeAssignUser(Long departmentId,Long userId) {
    	if (StringUtils.isNotEmpty(departmentId)&&StringUtils.isNotEmpty(userId)) {
    		departmentService.deleteByDepartmentIdAndUid(departmentId, userId);
    		return renderSuccess("成功删除信息！");
    	}else {
    		return renderError("删除失败，删除操作出错！");
		}
	}
}
